package com.superbytecode.stencil.strategy.script;

import com.superbytecode.stencil.strategy.SQLScriptStrategy;
import com.superbytecode.stencil.strategy.SQLStrategyEnum;
import com.superbytecode.stencil.strategy.SQLStrategyFactory;
import com.superbytecode.stencil.entities.table.SQLColumn;
import com.superbytecode.stencil.entities.table.SQLTable;
import com.superbytecode.stencil.enums.DatabaseTypeEnum;
import com.superbytecode.stencil.utils.MapUtil;
import com.superbytecode.stencil.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * All rights Reserved, Designed By www.super-master.com
 *
 * @ProjectName: magician
 * @Package: com.superbytecode.magician.strategy.script
 * @ClassName: MySQLBusinessService
 * @Description: [mysql数据库执行sql脚本策略实现]
 * <p> </p>
 * @Author: [Lance Ting]
 * @Date: 2024/10/8 14:39
 * @Version: V1.0
 * @Copyright: 2024 www.super-master.cn Inc. All rights reserved.
 * TODO: 注意,本文件Lance Ting所作,如果转载或使用请标明具体出处!
 **/
@Slf4j
@Service
public class MySQLScript implements SQLScriptStrategy, InitializingBean {
    /**
     * Invoked by the containing {@code BeanFactory} after it has set all bean properties
     * and satisfied {@link BeanFactoryAware}, {@code ApplicationContextAware} etc.
     * <p>This method allows the bean instance to perform validation of its overall
     * configuration and final initialization when all bean properties have been set.
     *
     * @throws Exception in the event of misconfiguration (such as failure to set an
     *                   essential property) or if initialization fails for any other reason
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        SQLStrategyEnum.sqlScriptStrategyMap.put(SQLStrategyEnum.MYSQL.getCode(), this);
    }
    //------------------------------------------------------------------------------------------------------------------

    /**
     * 获取数据库表结构
     * <p>
     * show table status from sys where `name` in ('sys_config', 'user');
     * <br>
     * ---------------+-------------------+
     * Name           |Value              |
     * ---------------+-------------------+
     * Name           |sys_config         |
     * Engine         |InnoDB             |
     * Version        |10                 |
     * Row_format     |Dynamic            |
     * Rows           |6                  |
     * Avg_row_length |2730               |
     * Data_length    |16384              |
     * Max_data_length|0                  |
     * Index_length   |0                  |
     * Data_free      |0                  |
     * Auto_increment |                   |
     * Create_time    |2023-08-16 17:40:57|
     * Update_time    |                   |
     * Check_time     |                   |
     * Collation      |utf8_general_ci    |
     * Checksum       |                   |
     * Create_options |                   |
     * Comment        |                   |
     * ---------------+-------------------+
     * </p>
     *
     * @param databaseName  数据库名
     * @param schTableNames 数据表名
     * @return 脚本
     */
    @Override
    public String obtainSQLShowTableScript(String databaseName, String... schTableNames) {
        // 兼容dbName包含'-'字段会报错的情况, sys-user => `sys-user`
        databaseName = databaseName.contains("-") ? String.format("`%s`", databaseName) : databaseName;
        StringBuilder scriptBuilder = new StringBuilder("show table status from  ").append(databaseName);
        if (!ArrayUtils.isEmpty(schTableNames)) {
            // 拼接sql脚本的查询条件
            List<String> scriptConditions = new ArrayList<>();
            Arrays.asList(schTableNames).forEach(condition -> scriptConditions.add("'" + condition + "'"));
            scriptBuilder.append(" where `name` in (").append(String.join(", ", scriptConditions)).append(")");
        }
        return scriptBuilder.append(";").toString();
    }

    /**
     * 构建SQL数据表名称/注解
     *
     * @param content 表信息
     *                <p>包含表名、注解等</p>
     * @return 表信息
     */
    @Override
    public SQLTable obtainSQLTableDefinition(Map<String, Object> content) {
        SQLTable sqlTable = new SQLTable();
        String name = MapUtil.obtainIgnoreCaseString(content, "NAME");
        String comment = MapUtil.obtainIgnoreCaseString(content, "COMMENT", name);
        sqlTable.setTableName(name);
        sqlTable.setComments(comment);
        return sqlTable;
    }

    /**
     * 获取数据库表属性列列表
     * <p>
     * show full columns from sys_config;
     * <br>
     * ----------+-------------------------------+
     * Name      |Value                          |
     * ----------+-------------------------------+
     * Field     |variable                       |
     * Type      |varchar(128)                   |
     * Collation |utf8_general_ci                |
     * Null      |NO                             |
     * Key       |PRI                            |
     * Default   |                               |
     * Extra     |                               |
     * Privileges|select,insert,update,references|
     * Comment   |                               |
     * ----------+-------------------------------+
     * </p>
     *
     * @param tableName 数据表名
     * @return 查询表数据脚本
     */
    @Override
    public String obtainSQLShowColumnScript(@NotNull(message = "table name is must be not empty") String tableName) {
        return String.format("show full columns from `%s`;", tableName);
    }

    /**
     * 构建SQL属性定义
     *
     * @param contentMap 表属性列信息
     *                   <p>数据库不同，包含属性也不同</p>
     * @return 表信息
     */
    @Override
    public SQLColumn obtainSQLColumnDefinition(Map<String, Object> contentMap) {
        SQLColumn sqlColumn = new SQLColumn();
        sqlColumn.setColumnName(MapUtil.obtainIgnoreCaseString(contentMap, "FIELD"));
        boolean isIdentity = StringUtil.equalsIgnoreCase("auto_increment", MapUtil.obtainIgnoreCaseString(contentMap, "EXTRA"));
        sqlColumn.setIsIdentity(isIdentity);
        boolean isPk = StringUtil.equalsIgnoreCase("pri", MapUtil.obtainIgnoreCaseString(contentMap, "KEY"));
        sqlColumn.setIsPrimaryKey(isPk);
        // 数据库类型以及版本
        String originalType = MapUtil.obtainIgnoreCaseString(contentMap, "TYPE");
        // 过滤数据列出现"int unsigned"、"varchar(64)"等特殊数据（转换为 int、varchar），导致解析失败
        originalType = StringUtil.filterFirstKeyword(originalType, " ", "(");
        String version = MapUtil.obtainIgnoreCaseString(contentMap, "LTS", "8.0");
        String sqlType = SQLStrategyFactory.ofSQLGenericType(DatabaseTypeEnum.MYSQL5.getCategoryCode(), version, originalType);
        sqlColumn.setColumnType(sqlType);
        //
        String comment = MapUtil.obtainIgnoreCaseString(contentMap, "COMMENT");
        sqlColumn.setComments(comment);
        return sqlColumn;
    }
}